<?php
include("const.php");
require("function.php");
if (!defined("VHOSTS_PATH")) {
    echo "请配置vhosts绝对路径";
    exit;
}
if (!file_exists(VHOSTS_PATH)) {
    echo "vhosts路径不存在";
    exit;
}
$file = $_GET["file"];
$Action = "insert";
$load = "";
$reloadFile = "";
if (isset($_POST['Action']) && $_POST['Action'] === 'update') {
    $fn = fopen(VHOSTS_PATH . $file, "w");
    fwrite($fn, $_POST['content']);
    $fn = fclose($fn);
    shell_exec(RELOAD_NGINX_CMD);
}
if (isset($_POST['Action']) && $_POST["Action"] == "insert") {
    $file = $_POST["file"];
    $fn = fopen(VHOSTS_PATH . $file, "w");
    fwrite($fn, $_POST['content']);
    $fn = fclose($fn);
    $load = "reload";
    $reloadFile = $file;
    shell_exec(RELOAD_NGINX_CMD);
}
$content = "";
$originContent = "";
if (isset($file) && trim($file) !== "") {
    $Action = "update";
    $filePath = VHOSTS_PATH . $file;
    [$originContent, $content] = getContent($filePath);
}
?>
<link rel="stylesheet" type="text/css" href="css/index.css">
<body>
<div id="conf-box">
    <?php echo $content; ?>
</div>
<form class="detail" method="post">
    <input type="hidden" id="Action" name="Action" value="<?php echo $Action; ?>">
    <input type="hidden" id="file" name="file" value="">
    <textarea id="content" name="content" class="content"><?php echo $originContent; ?></textarea>
</form>
</body>
<script src="js/index.js" type="text/javascript"></script>
<script>
    if ("<?php echo $load; ?>" === "reload") {
        window.parent.location.href = "index.php?reloadFile=<?php echo $reloadFile; ?>";
    }
    document.onkeydown = function (e) {
        let currentKey = 0;
        e = e || event || window.event;
        currentKey = e.keyCode || e.which || e.charCode;
        if (currentKey === 83 && (e.ctrlKey || e.metaKey)) {
            e.preventDefault();
            let Action = document.querySelector("#Action").value;
            if (Action === "update") {
                document.forms[0].submit();
            } else {
                let file_name = window.prompt("请输入保存的文件名(*.conf)：");
                if (file_name === null || file_name.trim() === "") {
                    alert("文件名不能为空");
                    return false;
                } else {
                    let id = file_name.replace(/\./g, "-");
                    if (window.parent.document.querySelector('#' + id) !== null) {
                        alert("配置文件已存在，请重新输入文件名");
                        return false;
                    }
                }
                document.querySelector('#file').value = file_name;
                document.forms[0].submit();
            }
        } else {
            if (currentKey === 27) {
                document.querySelector('#conf-box').style.display = "block";
                document.querySelector("form").style.display = "none";
            }
        }
    }
</script>